/**
 * 
 */
package com.effectivsocial.extension.properties;

import java.util.Scanner;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PropertyVariableParser {
	

	/**
	 * Replaces variables with the pattern ${aSystemPropertyValue}.
	 * 
	 * @param propertyValue
	 *            a string with the pattern ${asystem.property.value}
	 * @return replacement of propertyValue with the value of
	 *         System.getEnv(propertyValue);
	 */
	public String replaceVariables(String propertyValue) {
		final Scanner scanner = new Scanner(propertyValue);
		scanner.useDelimiter("\\$\\{");

		while (scanner.hasNext()) {
			String propertyName = scanner.next();

			final int endindex = propertyName.indexOf('}');

			if (-1 != endindex) {
				propertyName = propertyName.substring(0, endindex);
			} else {
				continue;
			}

			final String systemPropertyValue = System.getProperty(propertyName);

			if (null == systemPropertyValue) {
				log.warn("no such system property: {}", propertyName);
			} else {
				propertyValue = propertyValue.replace(
						"${" + propertyName + "}", systemPropertyValue);
			}
		}

		return propertyValue;
	}
}
